﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using Notes.Model;
using System.ComponentModel;
using Notes.Helpers;
using System.Collections.Specialized;

namespace Notes.ViewModels
{
    public class EditViewModel : INotifyPropertyChanged
    {
        private bool _IsDataLoaded;
        public bool IsDataLoaded
        {
            get
            {
                return _IsDataLoaded;
            }
            private set
            {
                _IsDataLoaded = value;
                NotifyPropertyChanged("IsDataLoaded");
            }
        }

        private bool _IsProgressVisible = false;
        public bool IsProgressVisible
        {
            get
            {
                return _IsProgressVisible;
            }
            set
            {
                _IsProgressVisible = value;
                NotifyPropertyChanged("IsProgressVisible");
            }
        }

        private Note _Note;
        public Note Note
        {
            get 
            {
                return _Note;
            }
            private set
            {
                _Note = value;
                NotifyPropertyChanged("Note");
            }
        }

        private ObservableCollection<Photo> _Photos;
        public ObservableCollection<Photo> Photos
        {
            get
            {
                return _Photos;
            }
            private set
            {
                _Photos = value;
                NotifyPropertyChanged("Photos");
            }
        }

        public EditViewModel() 
        {
            this.Photos = new ObservableCollection<Photo>();
            this.Note = new Note();
        }

        public void LoadNote(int SelectedIndex)
        {
            this.IsProgressVisible = true;
            this.Note = App.MainViewModel.Notes[SelectedIndex];

            var PhotosInDB = from Photo i in App.db.Photos where (i.NoteId == Note.Id) && (i.Deleted != true) select i;
            Photos = new ObservableCollection<Photo>(PhotosInDB);
            foreach (Photo i in Photos)
            {
                try
                {
                    if (App.file.FileExists(i.FileName))
                    {
                        using (IsolatedStorageFileStream stream = App.file.OpenFile(i.FileName, FileMode.Open))
                        {
                            i.Bitmap = new BitmapImage();
                            i.Bitmap.SetSource(stream);
                            stream.Close();
                            stream.Dispose();
                        }
                    }
                }
                catch (Exception e) {
                    Messenger.ShowMessage("Error", "File " + i.FileName + ". " + e.Message);
                }
            }

            this.IsDataLoaded = true;
            this.IsProgressVisible = false;
        }

        public void LoadNote()
        {
            this.Note = new Note();
        }

        internal void SaveNote(Note note)
        {
            this.IsProgressVisible = true;
            // save note
            Note.Title = note.Title;
            Note.Text = note.Text;
            Note.Edited = DateTime.Now;
            Note.CategoryId = 0;
            if (Note.Id == 0)
            {
                App.db.Notes.InsertOnSubmit(Note);
            }
            App.db.SubmitChanges();

            // save photos
            foreach (Photo i in Photos)
            {
                // to database
                i.NoteId = Note.Id;
                i.Edited = DateTime.Now;
                if (i.Id == 0)
                    App.db.Photos.InsertOnSubmit(i);
                // to isolatedstorage
                if (App.file.FileExists(i.FileName))
                    App.file.DeleteFile(i.FileName);
                IsolatedStorageFileStream myFileStream = App.file.CreateFile(i.FileName);
                WriteableBitmap writablebitmap = new WriteableBitmap(i.Bitmap);
                writablebitmap.SaveJpeg(myFileStream, i.Bitmap.PixelWidth, i.Bitmap.PixelHeight, 0, 95);
                myFileStream.Close();
            }
            App.db.SubmitChanges();
            this.IsProgressVisible = false;
        }

        public void DeleteNote()
        {
            this.IsProgressVisible = true;
            if (Note.Id > 0)
            {
                if (MessageBox.Show(AppResources.strMessageTextConfirmDelete, AppResources.strMessageTitleWarning, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    Note.Edited = DateTime.Now;
                    Note.Deleted = true;
                    App.db.SubmitChanges();
                    (App.Current as App).RootFrame.GoBack();
                    (App.Current as App).RootFrame.RemoveBackEntry();
                    foreach(Photo p in this.Photos)
                    {
                        DeletePhoto(p);
                    }
                }
            }
            this.Photos = new ObservableCollection<Photo>();
            this.IsProgressVisible = false;
        }

        public void DeletePhoto(Photo p)
        {
            if (p.Id > 0)
            {
                if (MessageBox.Show(AppResources.strMessageTextConfirmDelete, AppResources.strMessageTitleWarning, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    p.Deleted = true;
                    p.Edited = DateTime.Now;
                    App.db.SubmitChanges();
                }
            }
        }

        public void AddPhoto(Photo p)
        {
            //var photos = from pp in this.Photos select pp;
            //photos.ToList().Add(p);
            //this.Photos = new ObservableCollection<Photo>(photos);
            this.Photos.Add(p);
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }
}
